package cc.vv.baselibrary.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.util.ColorUtil;
import cc.vv.baselibrary.util.ImageUtil;
import cc.vv.lkbasecomponent.util.LKScreenUtil;
import cc.vv.lkbasecomponent.util.LKStringUtil;
import cc.vv.lkimagecomponent2.LKImage;
import cc.vv.lkimagecomponent2.loaderplugin.TargetViewCallback;

/**
 * 头像显示控件
 *
 * @author dup dupeng@vv.cc
 * @date 2018/3/21
 */
public class LKAvatarView extends RelativeLayout {

    private int mBorderWidth = 0;
    private int mBorderColor = Color.WHITE;
    private int mFillColor = ColorUtil.setBCColor(R.color.color_E31E26);
    private boolean mBorderOverlay = false;
    private int mTextColor = Color.WHITE;
    private int mTextSize = 12;

    private final Context context;
    private TextView tv_avatar;
    private LKCircleImageView iv_avatar;


    public LKAvatarView(Context context) {
        this(context, null);
    }

    public LKAvatarView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LKAvatarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        LayoutInflater factory = LayoutInflater.from(context);
        initView(factory, attrs, defStyleAttr);
    }

    private void initView(LayoutInflater factory, AttributeSet attrs, int defStyleAttr) {
        View view = factory.inflate(R.layout.view_lkaratar, null);
        tv_avatar = view.findViewById(R.id.tv_lkav_avatar);
        iv_avatar = view.findViewById(R.id.iv_lkav_avatar);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LKAvatarView, defStyleAttr, 0);
        mBorderWidth = a.getDimensionPixelSize(R.styleable.LKAvatarView_av_borderWidth, mBorderWidth);
        mBorderColor = a.getColor(R.styleable.LKAvatarView_av_borderColor, mBorderColor);
        mBorderOverlay = a.getBoolean(R.styleable.LKAvatarView_av_borderOverlay, mBorderOverlay);
        mFillColor = a.getColor(R.styleable.LKAvatarView_av_fillColor, mFillColor);
        mTextColor = a.getColor(R.styleable.LKAvatarView_av_textColor, mTextColor);
        mTextSize = LKScreenUtil.px2dp(a.getDimensionPixelSize(R.styleable.LKAvatarView_av_textSize, LKScreenUtil.dp2px(mTextSize)));
        CharSequence text1 = a.getText(R.styleable.LKAvatarView_av_text);
        String text = (text1 == null ? "" : text1.toString());

        iv_avatar.setBorderWidth(mBorderWidth);
        iv_avatar.setBorderColor(mBorderColor);
        iv_avatar.setBorderOverlay(mBorderOverlay);
        Drawable drawable = null;
        try {
            drawable = ImageUtil.bitmap2Drawable(context, BitmapFactory.decodeResource(getResources(), R.mipmap.default_user_avatar));
        } catch (Exception e) {
            e.printStackTrace();
            drawable = null;
        }
        if (null != drawable) {
            iv_avatar.setImageDrawable(drawable);
        } else {
            iv_avatar.setImageDrawable(new ColorDrawable(mFillColor));
        }
        tv_avatar.setTextColor(mTextColor);
        tv_avatar.setTextSize(mTextSize);
        tv_avatar.setText(text);

        a.recycle();
        this.addView(view);
    }

    public void setText(String text) {
        tv_avatar.setText(text);
        tv_avatar.setVisibility(View.VISIBLE);
        iv_avatar.setVisibility(View.GONE);
    }

    public void setTextColor(@ColorInt int color) {
        tv_avatar.setTextColor(color);
    }

    public void setTextSize(int size) {
        tv_avatar.setTextSize(size);
    }

    /**
     * 初始化头像数据
     *
     * @param text      昵称
     * @param url       头像
     * @param defAvatar 默认头像
     */
    public void initAvatar(String text, String url, int defAvatar) {
        initAvatar(text, url, defAvatar, mFillColor);
    }

    /**
     * 单独设置字体大小的加载
     *
     * @param text
     * @param url
     * @param defAvatar
     * @param textSize  sp
     */
    public void initAvatarWithSize(String text, String url, final int defAvatar, int textSize) {
        mTextSize = textSize;
        initAvatar(text, url, defAvatar);
    }

    /**
     * 单独设置字体大小的加载
     *
     * @param text
     * @param url
     * @param defAvatar
     * @param textSize  sp
     */
    public void initAvatarWithSize(String text, String url, final int defAvatar, int textSize, int fillColor) {
        mTextSize = textSize;
        initAvatar(text, url, defAvatar, fillColor);
    }


    /**
     * 初始化头像数据
     *
     * @param text      昵称
     * @param url       头像
     * @param defAvatar 默认头像
     */
    public void initAvatar(final String text, String url, final int defAvatar, final int fillColor) {
        String nick = text;
        if (TextUtils.isEmpty(nick)) {
            nick = LKStringUtil.getString(R.string.app_avatar_name);
        }

        tv_avatar.setVisibility(VISIBLE);
        iv_avatar.setVisibility(VISIBLE);
        iv_avatar.setImageDrawable(new ColorDrawable(fillColor));
        StringBuffer contentB = new StringBuffer();
        if (!TextUtils.isEmpty(nick)) {
            char start = nick.charAt(0);
            if (start >= 'A' && start <= 'z') {
                //英文开头,将开头一个字母大写
                contentB.append(charToUpperCase(start));
                if (nick.length() >= 2) {
                    //并将第二个加入
                    contentB.append(nick.charAt(1));
                }
            } else {
                //开头不是字母
                if (nick.length() >= 3) {
                    //取后两位
                    contentB.append(nick.substring(nick.length() - 2, nick.length()));
                } else {
                    contentB.append(nick);
                }
            }
        }
        tv_avatar.setText(contentB.toString());
        tv_avatar.setTextSize(mTextSize);

        if (!TextUtils.isEmpty(url)) {
            final String finalNick = nick;
            LKImage.load().load(url).gifRepeatCount(0).into(new TargetViewCallback<LKCircleImageView>(iv_avatar) {
                @Override
                public void onSuccess(Drawable drawable) {
                    tv_avatar.setVisibility(View.INVISIBLE);
                    iv_avatar.setImageDrawable(drawable);
                }

                @Override
                public void onStart(Drawable placeholder) {
                    super.onStart(placeholder);
                    tv_avatar.setVisibility(View.VISIBLE);
                    iv_avatar.setImageDrawable(new ColorDrawable(fillColor));
                }

                @Override
                public void onFail(Drawable errorDrawable) {
                    super.onFail(errorDrawable);
                    tv_avatar.setVisibility(VISIBLE);
                    iv_avatar.setImageDrawable(new ColorDrawable(fillColor));

                    StringBuffer contentB = new StringBuffer();
                    if (!TextUtils.isEmpty(finalNick)) {
                        char start = finalNick.charAt(0);
                        if (start >= 'A' && start <= 'z') {
                            //英文开头,将开头一个字母大写
                            contentB.append(charToUpperCase(start));
                            if (finalNick.length() >= 2) {
                                //并将第二个加入
                                contentB.append(finalNick.charAt(1));
                            }
                        } else {
                            //开头不是字母
                            if (finalNick.length() >= 3) {
                                //取后两位
                                contentB.append(finalNick.substring(finalNick.length() - 2, finalNick.length()));
                            } else {
                                contentB.append(finalNick);
                            }
                        }
                    }
                }
            });
        }
    }


    /**
     * 设置本地资源
     *
     * @param resourseId
     */
    public void initAvatar(int resourseId) {
        tv_avatar.setVisibility(GONE);
        iv_avatar.setVisibility(VISIBLE);
        iv_avatar.setImageResource(resourseId);
    }

    /**
     * 设置Bitmap
     *
     * @param bitmap
     */
    public void initAvatar(Bitmap bitmap) {
        tv_avatar.setVisibility(GONE);
        iv_avatar.setVisibility(VISIBLE);
        iv_avatar.setImageBitmap(bitmap);
    }

    /**
     * 获取 imageView
     *
     * @return
     */
    public ImageView getImageView() {
        return iv_avatar;
    }


    /**
     * 转大写
     **/
    private char charToUpperCase(char ch) {
        if (ch <= 122 && ch >= 97) {
            ch -= 32;
        }
        return ch;
    }

}